<?php

namespace IDock\Insurance\TPBX\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\TPBX\TPBXEnums;
use IDock\Insurance\TPBX\Response\AllTPBXResponse;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllTPBXResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('GBK','UTF-8//IGNORE',$body);
        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $body = json_decode($body,true);
            $returnCode = $body['code'] ?? '';
            $message = $body['msg'] ?? '';
            $this->setBody($body);
            if(strpos($message,'重复投保') !== false){
                $this->repeat($message);
                if($this->printer->repeatInsuredFlg){
                    $this->printer->success = false;
                    $this->printer->repeatMessage = $message;
                    return  $this;
                }
            }
            if ($returnCode != '0000') {
                $this->setError($message);
                return  $this;
            }
        }

        return $this;
    }

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }
        $body = $this->getBody() ?? [];

        $ciMsg = $body['qtnBase']['platReturnMsgCI'] ?? '';
        $biMsg = $body['qtnBase']['platReturnMsgBusi'] ?? '';
        if(!empty($ciMsg) or !empty($biMsg)){
            $this->setError($biMsg."\n".$ciMsg);
            $this->printer->success = false;
            return $this;
        }
        //询价流程号
        $mainData = $body['basePart'] ?? [];

        //车船税
        if ($carShipTax = $body['vehicleTax'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['vehicleTaxAmount'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax['lateFeeAmount'] ?? '';
            $this->printer->carTaxPrinter->payBackTax = $carShipTax['vehicleTaxAmountLast'] ?? '';
        }
        $this->printer->argc['vin'] = $body['vehicle']['vehicleFrameNo'] ?? '';
        $ciData = $body['tpfApply'] ?? '';
        $this->printer->inquiryNo = $mainData['tpCalculateNo'] ?? '';//mainSlipNo
        //交强险
        $this->printer->ciPremiumPrinter->ciPremium = $ciData['totalActualPremium'] ?? '';
        $this->printer->ciPremiumPrinter->ciBasePremium = $ciData['totalStandardPremium'] ?? '';
        $this->printer->ciPremiumPrinter->ciDiscount = $ciData['totalRatioTp'] ?? '';
        $this->printer->ciPremiumPrinter->ciStartData = $ciData['effectiveDate'] ? date('Y-m-d H:i:s',strtotime($ciData['effectiveDate'])) :'';
        $this->printer->ciPremiumPrinter->ciEndData =   $ciData['expireDate'] ? date('Y-m-d H:i:s',strtotime($ciData['expireDate'])) :'';
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险评级','ciBizName',$ciData['bizName'] ?? '');
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强出险次数','efcLastPolicyNum',$ciData['claimRecordSize'] ?? '');

        $biData = $body['bizApply'] ?? '';
        $this->printer->biPremiumPrinter = new PremiumBIPrinter();
        $this->printer->biPremiumPrinter->biPremium = $biData['totalActualPremium'];
        $this->printer->biPremiumPrinter->biBasePremium = $biData['totalStandardPremium'] ?? '';
        $this->printer->biPremiumPrinter->biStartData = $biData['effectiveDate'] ? date('Y-m-d H:i:s',strtotime($biData['effectiveDate'])) :'';
        $this->printer->biPremiumPrinter->biEndData = $biData['expireDate'] ? date('Y-m-d H:i:s',strtotime($biData['expireDate'])) :'';
        $this->printer->biPremiumPrinter->biDiscount = $biData['totalRatioTP'] ?? '';
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险评级', 'biBizName', $biData['bizName'] ?? '');
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业出险次数', 'bizLastPolicyNum', $biData['claimRecordSize'] ?? '');
        
        $factorArr = $body['factorRatioList'] ?? [];
        foreach ($factorArr as $value){
            if($value['factorCode'] == 'F84'){
                $this->printer->ncdFactor = $value['ratioTp'] ?? '';
            }
            $this->printer->premiumFactorPrinter->ComFactorAppend(TPBXEnums::$factor[$value['factorCode'] ?? ''] ?? $value['factorCode'],$value['factorCode'],$value['ratioTp'] ?: $value['ratioOther']);
        }
        $loyalty = '新保';
        if($mainData['RenewalFlag'] ?? ''){
            $loyalty = '转保';
        }
        if($mainData['IsRenewal'] ?? ''){
            $loyalty = '续保';
        }
        $this->printer->premiumFactorPrinter->ComFactorAppend('交强险忠诚度','CIRenewalType',$loyalty);
        $this->printer->premiumFactorPrinter->ComFactorAppend('商业险忠诚度','BIRenewalType',$loyalty);
        //险种
        $riskArr = $body['coverageList'] ?? [];
        foreach ($riskArr as $kind) {
            $coverage = new PremiumCoveragePrinter();
            if(!empty($kind['coverageCode'])){
                $coverage->coverageCode = array_search($kind['coverageCode'], TPBXEnums::$coverageCode);
                $coverage->coverageName = $kind['coverageName'] ?? '';
                $coverage->premium = $kind['totalActualPremium'] ?? '';
                $coverage->amount = $kind['insuredAmount'] ?? '';
                $coverage->serviceTimes = $kind['serviceNum'] ?? '0';
                $this->printer->coverageListAppend($coverage);
            }
        }
        return $this;
    }

    /**
     * 重复投保
     * @param $errMsg
     */
    private function repeat($errMsg)
    {
        if (preg_match('/终保日期 ([\d\s:-]+)/', $errMsg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
            }
        }
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                if($coverage->coverageCode == 'C01001'){
                    continue;
                }
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }
            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }
    }
}
